package cn.test.rabbitmq.normal;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author hanchao
 * @date 2017/6/30 15:00
 */
public class DefaultDLXDirectConsumer {
    private static final String QUEUE_NAME = "test-queue-dlx-fa";
    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.1.170");
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setVirtualHost("han");
        Connection connection = factory.newConnection();
        final Channel channel = connection.createChannel();
        channel.exchangeDeclare("dir",BuiltinExchangeType.DIRECT);

        //AMQP.Queue.DeclareOk dc = channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        channel.queueDeclare("ztk-dead-letters", false, false, false, null);
        //auto ack下，即使异常，也会确认消息。所以在spring中，只能靠spring的未处理来死循环消息
//        channel.basicConsume(QUEUE_NAME, false, "tag", new DefaultConsumer(channel) {
//            @Override
//            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
//                System.out.println(new String(body));
//                channel.basicNack(envelope.getDeliveryTag(),false,false);
//            }
//        });

        channel.basicConsume("ztk-dead-letters", false, "tag", new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println(new String(body));
                channel.basicNack(envelope.getDeliveryTag(),false,true);
            }
        });


    }
}
